using System;
using System.Linq;
using System.Windows.Forms;
using Comteck.Dto.Sys;
using Comteck.Ktt.Services.Sys;
using Comteck.Linq;
using Comteck.Localization;
using Comteck.Winforms;
using Comteck.Winforms.Forms;
using DevExpress.XtraBars;
using ExpressMapper.Extensions;

namespace Comteck.Ktt.WinUI.Sys {
  /// <summary>
  /// 
  /// </summary>
  public partial class FrmParameterAdmin : FrmBase {
    private readonly IParameterService parameterService;
    private CKObservableCollection<ParameterDto> mainDataList;

    public FrmParameterAdmin(IParameterService parameterService) {
      this.parameterService = parameterService;
      InitializeComponent();
    }

    private void FrmParameterAdmin_Load(object sender, EventArgs e) {
      if (this.DesignMode) {
        return;
      }

      gcMain.DataSource = mainDataList = new CKObservableCollection<ParameterDto>();
    }

    private async void btnSearch_ItemClick(object sender, ItemClickEventArgs e) {
      // search
      ajaxLoad.Show();
      var result = await parameterService.GetAllAsync();
      ajaxLoad.Hide();

      result.ToList().MapTo(mainDataList, x => x.Id, x => x.Id);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void btnSave_ItemClick(object sender, ItemClickEventArgs e) {
      gvMain.CloseEditor();

      // 选中的
      var rows = mainDataList.DataSource?.ToList();
      if (rows.IsNullOrEmpty()) {
        return;
      }

      var dialog = this.ShowMsg(BaseResources.Save_Confirm, null, MessageBoxButtons.YesNo,
        MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

      if (dialog == DialogResult.No) {
        return;
      }

      ajaxLoad.Show();
      try {
        await parameterService.SaveBatchAsync(rows);
        this.ShowMsg(BaseResources.Save_Success);
      } catch (Exception ex) {
        this.ShowMsg(BaseResources.Save_Failed_Reason, ex.Message);
      }
      ajaxLoad.Hide();
    }

    #region export

    /// <summary>
    /// 导出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnExport_ItemClick(object sender, ItemClickEventArgs e) {
      gvMain.ExportDialog();
    }

    #endregion

    #region close

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnClose_ItemClick(object sender, ItemClickEventArgs e) {
      this.Close();
    }

    #endregion
  }
}
